package com.leyou.page.service.impl;

import com.leyou.item.pojo.*;
import com.leyou.page.clients.CategoryClient;
import com.leyou.page.clients.GoodsClient;
import com.leyou.page.clients.SpecificationClient;
import com.leyou.page.service.PageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: Saka
 * Date: 2019/2/19
 * Time: 17:05
 */
@Service
public class PageServiceImpl implements PageService {

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private SpecificationClient specificationClient;


    @Override
    public Map<String, Object> toPage(Long spuId) {


            Map<String, Object> map = new HashMap<>();

            //先查spu
            Spu spu = goodsClient.querySpuById(spuId);
            map.put("spu", spu);

            SpuDetail spuDetail = this.goodsClient.querySpuDetailById(spuId);
            map.put("spuDetail", spuDetail);
            List<Sku> skus = this.goodsClient.querySkuBySpuId(spuId);
            map.put("skus", skus);

            //准备商品分类
            List<Category> categories = getCategories(spu);
            if (null!=categories) {
                map.put("categories", categories);
            }

            //准备品牌数据
            //TODO

            //查询规格组及组内参数
            List<SpecGroup> specGroups = this.specificationClient.querySpecsByCid(spu.getCid3());
            map.put("specGroups", specGroups);

            //查询商品分类下的特有规格参数
            List<SpecParam> specParams = this.specificationClient.querySpecParam(null, spu.getCid3(), false, null);

            //处理成id:name格式的键值对
            Map<Long, String> paramMap = new HashMap<>();
            specParams.forEach(specParam -> {
                paramMap.put(specParam.getId(), specParam.getName());//机身颜色,内存

            });
            map.put("paramMap", paramMap);


            return map;

    }

    private List<Category> getCategories(Spu spu) {


            List<String> names = this.categoryClient.queryNameByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            Category c1 = new Category();
            c1.setName(names.get(0));
            c1.setId(spu.getCid1());

            Category c2 = new Category();
            c2.setName(names.get(1));
            c2.setId(spu.getCid2());

            Category c3 = new Category();
            c3.setName(names.get(2));
            c3.setId(spu.getCid3());

            return Arrays.asList(c1, c2, c3);

    }


}
